package com.example.homework9;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.widget.Button;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.example.homework9.service.MusicService2;

public class Fragment4_2 extends Fragment {
    public Fragment4_2(){
        super(R.layout.fragment4_2);
    }

    private MyConn myConn;
    private Button playMusic2Button;
    private Button nextMusic2Button;
    private Button pauseMusic2Button;

    public class MyConn implements ServiceConnection {
        public MusicService2.MyBinder myBinder = null;
        @Override
        public void onServiceConnected(ComponentName name, IBinder service){
            myBinder = (MusicService2.MyBinder)service;
        }

        @Override
        public void onServiceDisconnected(ComponentName name){

        }

    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState){
        super.onViewCreated(view, savedInstanceState);

        Intent intent = new Intent(getActivity(), MusicService2.class);
        getActivity().startService(intent);

        if(myConn == null){
            myConn = new MyConn();
            intent = new Intent(getActivity(), MusicService2.class);
            getActivity().bindService(intent, myConn,0);
        }

        playMusic2Button=getView().findViewById(R.id.playMusic2Button);
        playMusic2Button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(myConn.myBinder == null){
                    return;
                }
                myConn.myBinder.play();
            }
        });

        nextMusic2Button=getView().findViewById(R.id.nextMusic2Button);
        nextMusic2Button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(myConn.myBinder == null){
                    return;
                }
                myConn.myBinder.next();
            }
        });

        pauseMusic2Button=getView().findViewById(R.id.pauseMusic2Button);
        pauseMusic2Button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(myConn.myBinder == null){
                    return;
                }
                myConn.myBinder.pause();
            }
        });
    }
}